package com.longcai.piaojia.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.longcai.piaojia.BaseApplication;
import com.longcai.piaojia.R;
import com.longcai.piaojia.adapter.LatestOrderAdapter;
import com.longcai.piaojia.adapter.LatestOrderDateadapter;
import com.longcai.piaojia.conn.Conn;
import com.longcai.piaojia.conn.LatestOrderDateGet;
import com.longcai.piaojia.conn.LatestOrderSurePost;
import com.longcai.piaojia.conn.LatestOrderTimeGet;
import com.longcai.piaojia.conn.LatestOrderToolsGet;
import com.longcai.piaojia.dialog.DateTimePickDialogBefore;
import com.longcai.piaojia.util.MyToast;
import com.longcai.piaojia.util.Validator;
import com.longcai.piaojia.widget.NoScrollGridView;
import com.longcai.piaojia.widget.NoScrollListView;
import com.zcx.helper.bound.BoundView;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.scale.ScaleScreenHelperFactory;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/1/9.
 */
public class LatestOrderActivity extends BaseActivity implements LatestOrderAdapter.LatestAddOrMinus, View.OnClickListener, DateTimePickDialogBefore.ChooseDate {

    @BoundView(R.id.latest_order_lv) private NoScrollListView latest_order_lv;
    @BoundView(R.id.latest_order_total_tv) private TextView latest_order_total_tv;
    @BoundView(R.id.latest_order_rl) private RelativeLayout latest_order_rl;
    @BoundView(R.id.latest_order_tv) private TextView latest_order_tv;
    @BoundView(R.id.latest_order_nsgv) private NoScrollGridView latest_order_nsgv;

    @BoundView(R.id.latest_order_num_ll) private LinearLayout latest_order_num_ll;
    @BoundView(R.id.latest_order_time_rl) private RelativeLayout latest_order_time_rl;
    @BoundView(R.id.latest_order_time_tv) private TextView latest_order_time_tv;
    @BoundView(R.id.latest_order_num_tv) private TextView latest_order_num_tv;
    @BoundView(R.id.latest_order_name_et) private EditText latest_order_name_et;
    @BoundView(R.id.latest_order_child_name_et) private EditText latest_order_child_name_et;
    @BoundView(R.id.latest_order_phone_et) private EditText latest_order_phone_et;
    @BoundView(R.id.latest_order_idcard_et) private EditText latest_order_idcard_et;

    @BoundView(R.id.latest_order_manber_child_name_ll) private LinearLayout latest_order_manber_child_name_ll;

    @BoundView(R.id.latest_order_with_child_sel_ll) private LinearLayout latest_order_with_child_sel_ll;
    @BoundView(R.id.latest_order_with_child_sel_iv) private ImageView latest_order_with_child_sel_iv;

    @BoundView(R.id.latest_order_with_child_no_ll) private LinearLayout latest_order_with_child_no_ll;
    @BoundView(R.id.latest_order_with_child_no_iv) private ImageView latest_order_with_child_no_iv;

    @BoundView(R.id.latest_order_tools_sel_ll) private LinearLayout latest_order_tools_sel_ll;
    @BoundView(R.id.latest_order_tools_sel_iv) private ImageView latest_order_tools_sel_iv;

    @BoundView(R.id.latest_order_tools_no_ll) private LinearLayout latest_order_tools_no_ll;
    @BoundView(R.id.latest_order_tools_no_iv) private ImageView latest_order_tools_no_iv;


    @BoundView(R.id.latest_order_damage_tv) private TextView latest_order_damage_tv;
    @BoundView(R.id.latest_order_use_tools_show_ll) private LinearLayout latest_order_use_tools_show_ll;
    private List<LatestOrderToolsGet.ToolsEntity> lists = new ArrayList<>();
    private List<LatestOrderTimeGet.OrderDateEntity> dateLists = new ArrayList<>();
    private LatestOrderAdapter adapter;
    private LatestOrderDateadapter dateAdapter;
    private int selPos = -1;
    private Bundle bundle;
    private LatestOrderTimeGet.LatestOrderDateEntity mlatestOrderDateEntity;
    private LatestOrderToolsGet.OrderToolEntity mOrderToolEntity;
    private LatestOrderDateGet.OrderTimeEntity mOrderTimeEntity;

    private String total = "0";

    private int childType = 0;
    private int toolsType = 0;

    private LatestOrderSurePost latestOrderSurePost = new LatestOrderSurePost(new AsyCallBack<String>() {

        @Override
        public void onSuccess(String toast, int type, String s) throws Exception {

            if (toolsType == 1) {

                Bundle bundle = new Bundle();

                bundle.putString("truePrice", total);
                bundle.putString("orderNum", s);

                startActivity(new Intent(LatestOrderActivity.this, LatestPayActivity.class).putExtras(bundle));

            } else {

                startActivity(new Intent(LatestOrderActivity.this, MyAppointmentActivity.class));

            }

            BaseApplication.INSTANCE.finishActivity(LatestActivity.class, LatestDetailActivity.class, LatestOrderActivity.class);

            Toast.makeText(context, toast, Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onFail(String toast, int type) throws Exception {

            Toast.makeText(context, toast, Toast.LENGTH_SHORT).show();

        }
    });

    //装备  工具列表数据
    private LatestOrderToolsGet latestOrderToolsGet = new LatestOrderToolsGet(new AsyCallBack<LatestOrderToolsGet.OrderToolEntity>() {

        @Override
        public void onSuccess(String toast, int type, LatestOrderToolsGet.OrderToolEntity orderToolEntity) throws Exception {

            mOrderToolEntity = orderToolEntity;

            lists.addAll(orderToolEntity.toolsEntityList);

            adapter.notifyDataSetChanged();
        }

        @Override
        public void onFail(String toast, int type) throws Exception {


        }
    });

    //时间列表
    private LatestOrderTimeGet latestOrderTimeGet = new LatestOrderTimeGet(new AsyCallBack<LatestOrderTimeGet.LatestOrderDateEntity>() {

        @Override
        public void onSuccess(String toast, int type, LatestOrderTimeGet.LatestOrderDateEntity latestOrderDateEntity) throws Exception {

            dateLists.clear();

            mlatestOrderDateEntity = latestOrderDateEntity;

            dateLists.addAll(latestOrderDateEntity.orderDateEntityList);

            dateAdapter.selPosition = -1;

            selPos = -1;

            dateAdapter.notifyDataSetChanged();

            latest_order_num_tv.setVisibility(View.GONE);

        }

        @Override
        public void onFail(String toast, int type) throws Exception {


        }

    });

    //日期选择 限制数据
    private LatestOrderDateGet latestOrderDateGet = new LatestOrderDateGet(new AsyCallBack<LatestOrderDateGet.OrderTimeEntity>() {

        @Override
        public void onSuccess(String toast, int type, LatestOrderDateGet.OrderTimeEntity orderTimeEntity) throws Exception {

            mOrderTimeEntity = orderTimeEntity;
        }

        @Override
        public void onFail(String toast, int type) throws Exception {

            MyToast.show(context, toast, Toast.LENGTH_SHORT);
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_latest_order);

        setBackTrue();

        setTitleName(getString(R.string.latest_detail_order_text));

        bundle = getIntent().getExtras();

        latest_order_lv.setAdapter(adapter = new LatestOrderAdapter(context, lists));

        latest_order_nsgv.setHorizontalSpacing(ScaleScreenHelperFactory.getInstance().getWidthHeight(20));
        latest_order_nsgv.setVerticalSpacing(ScaleScreenHelperFactory.getInstance().getWidthHeight(20));

        latest_order_nsgv.setAdapter(dateAdapter = new LatestOrderDateadapter(context, dateLists));

        latest_order_nsgv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (selPos != position && !dateLists.get(position).stock.equals("0")) {

                    dateAdapter.selPosition = position;

                    dateAdapter.notifyDataSetChanged();

                    selPos = position;

                    latest_order_num_tv.setText("（剩余" + dateLists.get(position).stock + "个名额）");

                    latest_order_num_tv.setVisibility(View.VISIBLE);
                }

            }
        });


        latestOrderDateGet.id = bundle.getString("id");
        latestOrderDateGet.execute(this);

        latestOrderToolsGet.id = bundle.getString("id");
        latestOrderToolsGet.execute(this);

        latest_order_rl.setOnClickListener(this);
        latest_order_with_child_sel_ll.setOnClickListener(this);
        latest_order_with_child_no_ll.setOnClickListener(this);
        latest_order_tools_sel_ll.setOnClickListener(this);
        latest_order_tools_no_ll.setOnClickListener(this);
        latest_order_time_rl.setOnClickListener(this);
        latest_order_damage_tv.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.latest_order_rl://提交按钮

                String mDate = latest_order_time_tv.getText().toString();
                String mName = latest_order_name_et.getText().toString();
                String mPhone = latest_order_phone_et.getText().toString();
                String mIdCard = latest_order_idcard_et.getText().toString();
                String mChildName = latest_order_child_name_et.getText().toString();

                if (TextUtils.isEmpty(mDate)) {

                    MyToast.show(context, "请选择日期", Toast.LENGTH_SHORT);
                    return;
                }

                if (selPos == -1) {

                    MyToast.show(context, "请选择时间", Toast.LENGTH_SHORT);
                    return;
                }

                if (TextUtils.isEmpty(mName)) {

                    MyToast.show(context, "请输入姓名", Toast.LENGTH_SHORT);
                    return;
                }

                if (TextUtils.isEmpty(mPhone)) {

                    MyToast.show(context, "请输入电话号码", Toast.LENGTH_SHORT);
                    return;
                }

                if (!Validator.isMobile(mPhone)) {

                    MyToast.show(context, "电话号码不正确", Toast.LENGTH_SHORT);
                    return;
                }

                if (TextUtils.isEmpty(mIdCard)) {

                    MyToast.show(context, "请输入身份证号码", Toast.LENGTH_SHORT);
                    return;
                }

                if (!Validator.isIDCard(mIdCard)) {

                    MyToast.show(context, "身份证号码不正确", Toast.LENGTH_SHORT);
                    return;
                }

                if (TextUtils.isEmpty(mChildName) && childType == 1) {

                    MyToast.show(context, "请输入孩子姓名", Toast.LENGTH_SHORT);
                    return;
                }


                JSONObject object = new JSONObject();

                try {

                    object.put("user_id", BaseApplication.BasePreferences.readUserId());
                    object.put("title", bundle.getString("title"));
                    object.put("p_id", bundle.getString("id")); //活动ID
                    object.put("p_aid", dateLists.get(selPos).id); //活动属性ID
                    object.put("datetimes", mDate);
                    object.put("time_tip", dateLists.get(selPos).time_tip);
                    object.put("starttime", dateLists.get(selPos).starttime);
                    object.put("endtime", dateLists.get(selPos).endtime);
                    object.put("name", mName);
                    object.put("mobile", mPhone);
                    object.put("idcart", mIdCard);
                    object.put("ischild", childType);//是否带儿童1是0否
                    object.put("child_name", childType == 1 ? mChildName : "");

                    if (!(Float.parseFloat(total) > 0)) {

                        toolsType = 0;
                    }

                    object.put("istool", toolsType);//是否 1是0否
                    object.put("amount", toolsType == 1 ? total : 0);
                    object.put("payway", "未支付");

                    JSONArray array = new JSONArray();

                    if (toolsType == 1) {

                        for (int i = 0; i < lists.size(); i++) {

                            JSONObject toolsObject = new JSONObject();

                            toolsObject.put("title", lists.get(i).title);
                            toolsObject.put("price", lists.get(i).price);
                            toolsObject.put("attr", lists.get(i).attr);
                            toolsObject.put("number", lists.get(i).count);

                            array.put(toolsObject);

                        }

                    }

                    object.put("object_info", array);

                } catch (JSONException e) {
                    e.printStackTrace();
                }


                latestOrderSurePost.data = object.toString();
                latestOrderSurePost.execute(this);

                break;

            case R.id.latest_order_time_rl:

                if (mOrderTimeEntity != null) {

                    DateTimePickDialogBefore dialogBefore = new DateTimePickDialogBefore(this, latest_order_time_tv, mOrderTimeEntity.starttime, mOrderTimeEntity.endtime);

                    dialogBefore.dateTimePicKDialog(latest_order_time_tv);

                }


                break;

            case R.id.latest_order_with_child_sel_ll:

                childType = 1;

                latest_order_with_child_sel_iv.setImageResource(R.mipmap.latest_sel);
                latest_order_with_child_no_iv.setImageResource(R.mipmap.latest_no);

                latest_order_manber_child_name_ll.setVisibility(View.VISIBLE);

                break;

            case R.id.latest_order_with_child_no_ll:

                childType = 0;

                latest_order_with_child_sel_iv.setImageResource(R.mipmap.latest_no);
                latest_order_with_child_no_iv.setImageResource(R.mipmap.latest_sel);

                latest_order_manber_child_name_ll.setVisibility(View.GONE);

                latest_order_child_name_et.setText("");

                break;

            case R.id.latest_order_tools_sel_ll:

                toolsType = 1;

                latest_order_tools_sel_iv.setImageResource(R.mipmap.latest_sel);
                latest_order_tools_no_iv.setImageResource(R.mipmap.latest_no);

                if (lists.size() > 0) {

                    latest_order_use_tools_show_ll.setVisibility(View.VISIBLE);

                }
                break;

            case R.id.latest_order_tools_no_ll:

                total = "0"; // 当选择不用工具的时候  价格设为 0

                latest_order_total_tv.setText("0");

                for (int i = 0; i < lists.size(); i++) {

                    lists.get(i).count = 0;
                }

                adapter.notifyDataSetChanged();

                toolsType = 0;

                latest_order_tools_sel_iv.setImageResource(R.mipmap.latest_no);
                latest_order_tools_no_iv.setImageResource(R.mipmap.latest_sel);

                latest_order_use_tools_show_ll.setVisibility(View.GONE);

                latest_order_tv.setText(getString(R.string.latest_detail_submit_text));

                break;

            case R.id.latest_order_damage_tv:

                Bundle bundle = new Bundle();

                bundle.putString("title", "损坏赔偿");
                bundle.putString("url", Conn.SERVICE + Conn.ACTIVITY_COMPENSATION);

                startActivity(new Intent(this, WebActivity.class).putExtras(bundle));

                break;

        }

    }


    @Override
    public void add(int pos) {

        lists.get(pos).count += 1;

        BigDecimal mTotal = new BigDecimal(total);

        BigDecimal mPrice = new BigDecimal(lists.get(pos).price);

        total = mTotal.add(mPrice).toString();

        latest_order_total_tv.setText(total);

        adapter.notifyDataSetChanged();

        if (Float.parseFloat(total) > 0) {

            latest_order_tv.setText(context.getString(R.string.latest_order_pay_text));

        } else {

            latest_order_tv.setText(context.getString(R.string.latest_detail_submit_text));

        }

    }

    @Override
    public void minus(int pos) {

        if (lists.get(pos).count > 0) {

            lists.get(pos).count -= 1;

            BigDecimal mTotal = new BigDecimal(total);

            BigDecimal mPrice = new BigDecimal(lists.get(pos).price);

            total = mTotal.subtract(mPrice).toString();

            latest_order_total_tv.setText(total);

            adapter.notifyDataSetChanged();

            if (Float.parseFloat(total) > 0) {

                latest_order_tv.setText(context.getString(R.string.latest_order_pay_text));

            } else {

                latest_order_tv.setText(context.getString(R.string.latest_detail_submit_text));

            }

        }

    }


    @Override
    public void chooseDone(String dateTime) {

        latest_order_num_ll.setVisibility(View.VISIBLE);

        latestOrderTimeGet.id = bundle.getString("id");
        latestOrderTimeGet.time = dateTime;
        latestOrderTimeGet.execute(this);

    }
}
